package org.easyway.tiles.generic;

import static org.easyway.tiles.generic.GraphicBoard.tileHeight;
import static org.easyway.tiles.generic.GraphicBoard.tileWidth;
import static org.easyway.tiles.generic.GraphicBoard.worldHeight;
import static org.easyway.tiles.generic.GraphicBoard.worldWidth;

public class CopierTool {

	public static boolean copier;

	public static boolean startPos = true;

	public static GraphicBoard board;

	static int startx, starty;

	static int endx, endy;

	static CustomImage[][] cache;

	static int cachex, cachey;

	public static void onClick(int mx, int my) {
		int x = Math.min(worldWidth-1, Math.max(0, mx
				/ (int) (tileWidth / ZoomManager.getZoomFactor())));
		int y = Math.min(worldHeight-1, Math.max(0, my
				/ (int) (tileHeight / ZoomManager.getZoomFactor())));
		if (startPos) {
			startx = x;
			starty = y;
			startPos = false;
		} else {
			if (x >= startx) {
				endx = x;
			} else {
				endx = startx;
				startx = x;
			}
			if (y >= starty) {
				endy = y;
			} else {
				endy = starty;
				starty = y;
			}
			if (copier) {
				createCache();
				startPos = true;
				GenericMapEditor.setToolPaster();
			} else {
				paste();
				startPos = true;
			}
		}

	}

	private static void createCache() {
		cachex = endx - startx + 1;
		cachey = endy - starty + 1;
		cache = new CustomImage[cachex][cachey];
		for (int y, x = 0; x < cachex; ++x) {
			for (y = 0; y < cachey; ++y) {
				cache[x][y] = GraphicBoard.imageGrid[x + startx][y + starty];
			}
		}
	}

	private static void paste() {
		int sizex = endx - startx;
		int sizey = endy - starty;
		for (int y, x = 0; x <= sizex; ++x) {
			for (y = 0; y <= sizey; ++y) {
				// cache[x][y] = GraphicBoard.imageGrid[x+startx][y+starty];
				GraphicBoard.imageGrid[x + startx][y + starty] = cache[x
						% cachex][y % cachey];
			}
		}
		board.repaint();
	}
}
